using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.IoC;
using ShopPowerTemplate.Presentation.Mvc.Extensions;
using ShopPowerTemplate.Presentation.Mvc.Models;
using ShopPowerTemplate.Presentation.Mvc.ViewModels;
using ShopPowerTemplate.Services;

namespace ShopPowerTemplate.Presentation.Mvc.Controllers
{
	public partial class ImageControllerBase : BaseController
	{
		#region Members

        protected IImageService _imageService;
        protected IProductService _productService;

        #endregion

        #region Constructors

        public ImageControllerBase(IImageService imageService, IProductService productService)
        {
            _imageService = imageService;
            _productService = productService;
        }	

        #endregion

		#region Index

		// **************************************
        // URL: /Image
        // **************************************
		public virtual ActionResult Index()
		{
			IndexImageViewModel viewModel = new IndexImageViewModel();
			ViewBag.PageIndex = this.GetPageIndex();
            ViewBag.PageSize = this.GetPageSize();
			ViewBag.SearchValue = this.GetSearchValue();
		
			return View(viewModel);
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Load(string sidx, string sord, int page, int rows, string search, int mode = 1)
        {
            string searchValue = this.GetSearchValue();
            OrderBy orderBy = this.GetOrderBy();
            int pageIndex = this.GetPageIndex();
            int pageSize = this.GetPageSize();

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {                
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex(pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue(searchValue);
                pageIndex = 0;
                this.SetPageIndex(pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy(orderBy);
            }

            if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                orderBy = new OrderBy(sidx, sord == "asc");
                this.SetOrderBy(orderBy);
            }

            List<Image> searchList = _imageService.Search(searchValue, orderBy.Property, orderBy.Ascending, pageIndex, pageSize);
            int count = _imageService.SearchCount(searchValue);
            
			if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                pageIndex = this.GetPageIndex();
            }

            var data = new
            {
                total = Math.Ceiling((float)count/(float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from image in searchList     // Row data
                       select new
                       {
                           id = image.Id,                
                           cell = new string[] {
						   
                                image.Name,
								image.Description,
								image.SortOrder.ToString(),
								image.Product != null ? image.Product.IdentityDescription : string.Empty
								
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id)
        {
            try
            {
                _imageService.Remove(id);
            }
            catch (RemoveException ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
            return Content(string.Empty);
        }
		
		public virtual FileContentResult Report()
        {
            IList<Image> _imageList = _imageService.Search(this.GetSearchValue());            
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description;SortOrder;Product");

            // rows
            foreach (Image image in _imageList)
            {
                List<string> rowData = new List<string>() { image.Name, image.Description, image.SortOrder.ToString(), image.Product != null ? image.Product.IdentityDescription : string.Empty };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Image.csv");
        }
		

		#endregion

		#region Create

		// *******************************************
        // URL: /Image/Create
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Create()
        {
            Image image = new Image();
            CreateImageViewModel viewModel = Mapper.Map<Image, CreateImageViewModel>(image);
            List<Product> allProduct = _productService.FindAll();
            viewModel.ProductList = allProduct;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Create(CreateImageViewModel imageModel)
        {
            if (ModelState.IsValid)
            {
                Image image = new Image();
                AutoMapper.Mapper.Map<CreateImageViewModel, Image>(imageModel, image);
 
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];

                    if (inputTagName == "Data" && file.ContentLength > 0)
                    {
                        image.Data = Helpers.ZipUtil.Zip(file);
                    }
				}

				_imageService.Add(image);

                return RedirectToAction("Edit", new { id = image.Id});
            }
            else
            {
				List<Product> allProduct = _productService.FindAll();
				imageModel.ProductList = allProduct;

                return View(imageModel);
            }
		}
		

		#endregion

		#region Edit

		// *******************************************
        // URL: /Image/Edit/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Edit(int id)
        {
            Image image = _imageService.Find(id);
            EditImageViewModel viewModel = Mapper.Map<Image, EditImageViewModel>(image);
            List<Product> allProduct = _productService.FindAll();
            viewModel.ProductList = allProduct;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(EditImageViewModel imageModel)
        {
            if (ModelState.IsValid)
            {
                Image image = _imageService.Find(imageModel.Id);
                AutoMapper.Mapper.Map<EditImageViewModel, Image>(imageModel, image);
                
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];

                    if (inputTagName == "Data" && file.ContentLength > 0)
                    {
                        image.Data = Helpers.ZipUtil.Zip(file);
                    }
				}
				_imageService.Change(image);

                return RedirectToAction("Index");
            }
            else
            {
				List<Product> allProduct = _productService.FindAll();
				imageModel.ProductList = allProduct;

                return View(imageModel);
            }
		}
		

		#endregion

		#region Details

		// *******************************************
        // URL: /Image/Details/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Details(int id)
        {
            Image image = _imageService.Find(id);
            DetailsImageViewModel viewModel = Mapper.Map<Image, DetailsImageViewModel>(image);
            
			return View(viewModel);
        }
		

		#endregion

		#region Downloads

		public virtual ActionResult DownloadBinary(int id, string p)
		{
			Image image = _imageService.Find(id);
			byte[] contents = null;
			string filename = string.Empty;
			
	
			if(p == "Data")
			{
				contents = Helpers.ZipUtil.Unzip(image.Data, out filename);
			}
			

			return File(contents, Helpers.FileHelper.GetMimeType(filename), filename);
		}

		#endregion
	}
}
